package com.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.pojo.LocationPojo;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @version:java version 1.8
 * @Author:gzt
 * @description:
 * @date:2023-06-1416:23
 */

public class ChangeDataListener extends AnalysisEventListener<LocationPojo> {
    private List<LocationPojo> list = new LinkedList<>();

    /**
     * 这个每一条数据解析都会来调用
     */
    public void invoke(LocationPojo locationPojo, AnalysisContext analysisContext) {
        locationPojo.setE1(locationPojo.getA1());
        list.add(locationPojo);
    }

    /**
     * 所有数据读取完了调用
     */
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        list = list.stream().filter(t -> t.getB1() != null).collect(Collectors.toList());
        String jsonString = JSON.toJSONString(list);
        String replace =
                jsonString.replace('{', '[').replace('}', ']').replace('N', ' ').replaceAll("E0","E").replace('E', ' ').replaceAll(" ",
                        "");

        replace = replace.replaceAll("\"+\\w+\\d+\"+:", "").replaceAll("′","′,").replaceAll("′,\"","′\"");

        System.out.println("读取完毕 所有数据  " + replace);

        BufferedWriter bw;
        try {
            bw = new BufferedWriter(new FileWriter("./test.js"));
            bw.write(replace);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean hasAllFieldsWithValue(Object obj) throws IllegalAccessException {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            Object value = field.get(obj);

            if (value == null) {
                return false;
            }
        }

        return true;
    }

}

